import router from '@/router/index'
import nporgress from 'nprogress'
// 引入进度条样式
import 'nprogress/nprogress.css'
// 获取用户相关数据小仓库
import useUserStore from '../store/modules/user'
import pinia from '../store'
import { ElMessage, ElNotification } from 'element-plus'
import { SET_TOKEN, GET_TOKEN, DEL_TOKEN } from "@/utils/token";
let userStore = useUserStore(pinia)
import permissionCheck from '@/utils/permissionCheck'


/**
 * 路由鉴权
 */

// 全局前置守卫
router.beforeEach((to, from, next) => {
    nporgress.start()
    let token = localStorage.getItem('satoken')
    let userName = userStore.userName // null
    if (token) {
        if (to.path == '/guide') {
            next('/subject')
        }
        try {
            userStore.userInfo()
        } catch (error) {
            localStorage.removeItem('satoken')
            const expirationDate = new Date();
            expirationDate.setDate(expirationDate.getDate() - 1);
            document.cookie = `username=; expires=${expirationDate.toUTCString()}`;
        }
        if (userName) {
            // 用户已经登录, 获取用户信息，做信息持久化
            if (to.path == '/login') {
                next('/subject')
            }
            if (to.path == '/upload-subject') {
                // 判断是否有出题权限
                if (!permissionCheck(['subject:add', 'subject:upload'])) {
                    ElNotification.warning('暂无权限')
                    next(from.path)
                }
            }
        } 
    }
    next()
})


// 全局后置守卫
router.afterEach((to, from) => {
    nporgress.done()
})